import { useState } from 'react'
import { X, Check, Filter, ArrowUpDown } from 'lucide-react'
import { FilterOptions, SortOption, SortDirection } from '../utils/taskFilters'

interface TaskFilterPanelProps {
  isOpen: boolean
  onClose: () => void
  filters: FilterOptions
  sortBy: SortOption
  sortDirection: SortDirection
  onFiltersChange: (filters: FilterOptions) => void
  onSortChange: (sortBy: SortOption, direction: SortDirection) => void
  onReset: () => void
}

export default function TaskFilterPanel({
  isOpen,
  onClose,
  filters,
  sortBy,
  sortDirection,
  onFiltersChange,
  onSortChange,
  onReset
}: TaskFilterPanelProps) {
  const [activeTab, setActiveTab] = useState<'filter' | 'sort'>('filter')

  if (!isOpen) return null

  const priorityOptions = [
    { value: 'P0', label: '紧急', color: 'bg-red-100 text-red-700' },
    { value: 'P1', label: '高', color: 'bg-orange-100 text-orange-700' },
    { value: 'P2', label: '中', color: 'bg-blue-100 text-blue-700' },
    { value: 'P3', label: '低', color: 'bg-green-100 text-green-700' }
  ]

  const categoryOptions = [
    { value: 'work', label: '💼 工作' },
    { value: 'personal', label: '👤 个人' },
    { value: 'learning', label: '📚 学习' },
    { value: 'health', label: '🏃 健康' },
    { value: 'other', label: '📝 其他' }
  ]

  const statusOptions = [
    { value: 'pending', label: '未完成' },
    { value: 'completed', label: '已完成' }
  ]

  const dateRangeOptions = [
    { value: 'all', label: '全部时间' },
    { value: 'today', label: '今天' },
    { value: 'thisWeek', label: '本周' },
    { value: 'overdue', label: '已过期' },
    { value: 'noDate', label: '无日期' }
  ]

  const sortOptions = [
    { value: 'priority' as SortOption, label: '优先级' },
    { value: 'dueDate' as SortOption, label: '截止日期' },
    { value: 'createdAt' as SortOption, label: '创建时间' },
    { value: 'title' as SortOption, label: '标题' },
    { value: 'status' as SortOption, label: '完成状态' }
  ]

  const handlePriorityToggle = (priority: string) => {
    const newPriorities = filters.priorities.includes(priority)
      ? filters.priorities.filter(p => p !== priority)
      : [...filters.priorities, priority]
    onFiltersChange({ ...filters, priorities: newPriorities })
  }

  const handleCategoryToggle = (category: string) => {
    const newCategories = filters.categories.includes(category)
      ? filters.categories.filter(c => c !== category)
      : [...filters.categories, category]
    onFiltersChange({ ...filters, categories: newCategories })
  }

  const handleStatusToggle = (status: string) => {
    const newStatuses = filters.statuses.includes(status)
      ? filters.statuses.filter(s => s !== status)
      : [...filters.statuses, status]
    onFiltersChange({ ...filters, statuses: newStatuses })
  }

  const handleDateRangeChange = (dateRange: string) => {
    onFiltersChange({ ...filters, dateRange })
  }

  const handleSortOptionChange = (option: SortOption) => {
    if (option === sortBy) {
      // 切换排序方向
      onSortChange(option, sortDirection === 'asc' ? 'desc' : 'asc')
    } else {
      // 选择新的排序选项，默认升序
      onSortChange(option, 'asc')
    }
  }

  return (
    <div className="fixed inset-0 z-[60] bg-black bg-opacity-50 flex items-end">
      <div className="w-full bg-white rounded-t-xl max-h-[80vh] overflow-hidden">
        {/* 头部 */}
        <div className="flex items-center justify-between p-4 border-b border-gray-200">
          <h3 className="text-lg font-semibold text-gray-900">筛选和排序</h3>
          <button
            onClick={onClose}
            className="p-1 text-gray-500 hover:text-gray-700 transition-colors"
          >
            <X size={20} />
          </button>
        </div>

        {/* 标签页 */}
        <div className="flex border-b border-gray-200">
          <button
            onClick={() => setActiveTab('filter')}
            className={`flex-1 flex items-center justify-center gap-2 py-3 text-sm font-medium transition-colors ${
              activeTab === 'filter'
                ? 'text-blue-600 border-b-2 border-blue-600 bg-blue-50'
                : 'text-gray-500 hover:text-gray-700'
            }`}
          >
            <Filter size={16} />
            筛选
          </button>
          <button
            onClick={() => setActiveTab('sort')}
            className={`flex-1 flex items-center justify-center gap-2 py-3 text-sm font-medium transition-colors ${
              activeTab === 'sort'
                ? 'text-blue-600 border-b-2 border-blue-600 bg-blue-50'
                : 'text-gray-500 hover:text-gray-700'
            }`}
          >
            <ArrowUpDown size={16} />
            排序
          </button>
        </div>

        {/* 内容区域 */}
        <div className="overflow-y-auto max-h-[60vh]">
          {activeTab === 'filter' ? (
            <div className="p-4 space-y-6">
              {/* 优先级筛选 */}
              <div>
                <h4 className="text-sm font-medium text-gray-900 mb-3">优先级</h4>
                <div className="flex flex-wrap gap-2">
                  {priorityOptions.map(option => (
                    <button
                      key={option.value}
                      onClick={() => handlePriorityToggle(option.value)}
                      className={`px-3 py-2 rounded-full text-xs border transition-all ${
                        filters.priorities.includes(option.value)
                          ? `${option.color} border-current`
                          : 'bg-gray-50 text-gray-600 border-gray-200 hover:border-gray-300'
                      }`}
                    >
                      {filters.priorities.includes(option.value) && <Check size={12} className="inline mr-1" />}
                      {option.label}
                    </button>
                  ))}
                </div>
              </div>

              {/* 分类筛选 */}
              <div>
                <h4 className="text-sm font-medium text-gray-900 mb-3">分类</h4>
                <div className="flex flex-wrap gap-2">
                  {categoryOptions.map(option => (
                    <button
                      key={option.value}
                      onClick={() => handleCategoryToggle(option.value)}
                      className={`px-3 py-2 rounded-full text-xs border transition-all ${
                        filters.categories.includes(option.value)
                          ? 'bg-blue-600 text-white border-blue-600'
                          : 'bg-gray-50 text-gray-600 border-gray-200 hover:border-gray-300'
                      }`}
                    >
                      {filters.categories.includes(option.value) && <Check size={12} className="inline mr-1" />}
                      {option.label}
                    </button>
                  ))}
                </div>
              </div>

              {/* 状态筛选 */}
              <div>
                <h4 className="text-sm font-medium text-gray-900 mb-3">完成状态</h4>
                <div className="flex flex-wrap gap-2">
                  {statusOptions.map(option => (
                    <button
                      key={option.value}
                      onClick={() => handleStatusToggle(option.value)}
                      className={`px-3 py-2 rounded-full text-xs border transition-all ${
                        filters.statuses.includes(option.value)
                          ? 'bg-green-600 text-white border-green-600'
                          : 'bg-gray-50 text-gray-600 border-gray-200 hover:border-gray-300'
                      }`}
                    >
                      {filters.statuses.includes(option.value) && <Check size={12} className="inline mr-1" />}
                      {option.label}
                    </button>
                  ))}
                </div>
              </div>

              {/* 时间范围筛选 */}
              <div>
                <h4 className="text-sm font-medium text-gray-900 mb-3">时间范围</h4>
                <div className="space-y-2">
                  {dateRangeOptions.map(option => (
                    <button
                      key={option.value}
                      onClick={() => handleDateRangeChange(option.value)}
                      className={`w-full text-left px-3 py-2 rounded-lg text-sm transition-colors ${
                        filters.dateRange === option.value
                          ? 'bg-blue-600 text-white'
                          : 'bg-gray-50 text-gray-600 hover:bg-gray-100'
                      }`}
                    >
                      {filters.dateRange === option.value && <Check size={16} className="inline mr-2" />}
                      {option.label}
                    </button>
                  ))}
                </div>
              </div>
            </div>
          ) : (
            <div className="p-4 space-y-4">
              <h4 className="text-sm font-medium text-gray-900">排序方式</h4>
              <div className="space-y-2">
                {sortOptions.map(option => (
                  <button
                    key={option.value}
                    onClick={() => handleSortOptionChange(option.value)}
                    className={`w-full text-left px-3 py-3 rounded-lg text-sm transition-colors flex items-center justify-between ${
                      sortBy === option.value
                        ? 'bg-blue-50 text-blue-600 border border-blue-200'
                        : 'bg-gray-50 text-gray-600 hover:bg-gray-100'
                    }`}
                  >
                    <span>{option.label}</span>
                    {sortBy === option.value && (
                      <span className="text-xs text-blue-500">
                        {sortDirection === 'asc' ? '↑ 升序' : '↓ 降序'}
                      </span>
                    )}
                  </button>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* 底部操作 */}
        <div className="p-4 border-t border-gray-200 bg-gray-50">
          <div className="flex gap-3">
            <button
              onClick={onReset}
              className="flex-1 py-2 px-4 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-100 hover:text-gray-800 transition-colors"
            >
              重置
            </button>
            <button
              onClick={onClose}
              className="flex-1 py-2 px-4 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
            >
              应用
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}
